//
//  ViewController.m
//  HMDemo
//
//  Created by Air on 2017/6/9.
//  Copyright © 2017年 orvibo. All rights reserved.
//

#import "ViewController.h"
#import "ViewController+Interface.h"
#import "ViewController+Shortcuts.h"
#import <CoreSpotlight/CoreSpotlight.h>

@interface ViewController ()<UITableViewDelegate,UITableViewDataSource>

@property(nonatomic,strong)NSMutableArray *sceneArray;
@property(nonatomic,strong) IBOutlet UITableView *sceneTableView;

@end

@implementation ViewController


-(void)donateSceneInteration:(HMScene *)scene API_AVAILABLE(ios(12.0)){
    //if (@available(iOS 12.0, *)) {
    HMSceneIntent *intent = [[HMSceneIntent alloc]init];
    intent.sceneNo = scene.sceneNo;
    intent.sceneId = @(scene.sceneId);
    intent.sceneName = scene.sceneName;
    intent.uidArray = @[@"5ccf7f0a0a7a"];
    
    intent.icon = [[INObject alloc]initWithIdentifier:intent.sceneNo displayString:@"displayString"];
    [intent setImage:[INImage imageNamed:@"scene_icon_11"] forParameterNamed:@"icon"];
    
    intent.suggestedInvocationPhrase = scene.sceneName;
    
    //INShortcut *shortCuts = [[INShortcut alloc] initWithIntent:intent];
    
    
    INInteraction *interaction = [[INInteraction alloc] initWithIntent:intent response:nil];
    [interaction donateInteractionWithCompletion:^(NSError * _Nullable error) {
        NSLog(@"%@",error);
    }];
    //    } else {
    //        // Fallback on earlier versions
    //    }
}

//此方法返回一个 NSUserActivity 对象。
- (NSUserActivity *)activityWithScene:(HMScene *)scene{
    //根据plist文件的值，创建 UserActivity
    NSUserActivity *checkInActivity = [[NSUserActivity alloc] initWithActivityType:@"com.orvibo.cloudPlatform.scene"];
    
    //设置 YES，通过系统的搜索，可以搜索到该 UserActivity
    checkInActivity.eligibleForSearch = YES;
    
    //允许系统预测用户行为，并在合适的时候给出提醒。（搜索界面，屏锁界面等。）
    if (@available(iOS 12.0, *)) {
        checkInActivity.eligibleForPrediction = YES;
    }
    
    checkInActivity.title = scene.sceneName;
    
    //引导用户新建语音引导（具体效果见下图）
    if (@available(iOS 12.0, *)) {
        checkInActivity.suggestedInvocationPhrase = scene.sceneName;
    }
    /*
     https://www.cnblogs.com/jgCho/archive/2015/11/13/4961435.html
     **/
    CSSearchableItemAttributeSet * attributes = [[CSSearchableItemAttributeSet alloc] init];

    UIImage *icon = [UIImage imageNamed:@"scene_icon_11"];
    attributes.thumbnailData = UIImagePNGRepresentation(icon);

    attributes.contentDescription = @"执行情景";

    checkInActivity.contentAttributeSet = attributes;
    
//    UIView *v = [[UIView alloc]init];
//    self.userActivity = checkInActivity;
    return checkInActivity;
}




- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    [self loadData];
    [self login];
    
    //Donate userActivity
    //self.userActivity = [self donateSportActivity];
}

-(void)login{
    
    //NSString *userName = @"13686493579";
    NSString *userName = @"18620330995";
    NSString *password = @"123456";
    
    [HMSDK loginWithUserName:userName password:password completion:^(KReturnValue value) {
        
        if (value == KReturnValueSuccess){
            NSLog(@"登陆成功 Login success");
            
            [self loadData];
        }else{
            NSLog(@"登陆失败，错误码 Login failed：%d",value);
        }
    }
     ];
}

-(void)loadData1{
    self.sceneArray = [self interfaceArray];
    [self.sceneTableView reloadData];
}
-(void)loadData{
    
    NSMutableArray *scenes = [@[] mutableCopy];
    
    NSString *sql = [NSString stringWithFormat:@"select * from scene where familyId = '%@'",userAccout().familyId];
    queryDatabase(sql, ^(FMResultSet *rs) {
        
        HMScene *scene = [HMScene object:rs];
        [scenes addObject:scene];
        
        if (@available(iOS 12.0, *)) {
            [self donateSceneInteration:scene];
        } else {
            // Fallback on earlier versions
        }
    });
    self.sceneArray = scenes;
    [self.sceneTableView reloadData];
}




#pragma mark- UITableView Delegate&DataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.sceneArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSString *identifiter = @"sceneCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifiter];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identifiter];
    }
    
    HMScene *scene = self.sceneArray[indexPath.row];
    if ([scene isKindOfClass:[NSDictionary class]]) {
        cell.textLabel.text = ((NSDictionary *)scene)[@"name"];
        return cell;
    }
    cell.textLabel.text = scene.sceneName;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    HMScene *scene = self.sceneArray[indexPath.row];
    
    if ([scene isKindOfClass:[NSDictionary class]]) {
        VoidBlock block = ((NSDictionary *)scene)[@"selector"];
        if (block) {
            block();
        }
        return;
    }
    
    if (@available(iOS 12.0, *)) {
        [self handleSiriShortcut:scene];
    }
}

@end
